<?php
require_once('includes/config.php');
require_once('includes/openid.php');
session_start();
if (isset($_GET['logoff'])) {
	session_destroy();
	setcookie("id", "", -1);
	setcookie("oid", "", -1);
        echo '<meta http-equiv="refresh" content="0;url=index.php" />';
	exit();
}

if (isset($_POST['remember'])) { $_SESSION['remember']=$_POST['remember']; }

try {
    $openid = new LightOpenID;
    if(!$openid->mode) {
            $openid->identity = 'https://www.google.com/accounts/o8/id';      
            header('Location: ' . $openid->authUrl());
    } elseif($openid->mode == 'cancel') {
        echo 'User has canceled authentication!';
    } else {
	$conn = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS);
	$remember=$_SESSION['remember'];
        session_regenerate_id();
        $openid->validate();
        $attributes = $openid->getAttributes();
        mysql_select_db(MYSQL_DB);
	$oid=$openid->identity;
        $query = "SELECT id FROM `users` where openid = '".$oid."'";
        $results=mysql_query($query);
        $numrows=mysql_num_rows($results);
        if ($numrows==1) {
                $result=mysql_fetch_array($results);
                $_SESSION['SESS_ID']=$result['id'];
	        $_SESSION['sortitem']='id';
        	$_SESSION['sortorder']='';
        	$_SESSION['limit']='10';
		if ($remember == '1') {
	        	setcookie("id", $result['id'], time()+(60*60*24*14));
        		setcookie("oid", sha1($oid), time()+(60*60*24*14));
		}
        }
        else {
                $query = "INSERT INTO `users` (`openid`) VALUES ('".$oid."')";
                $results=mysql_query($query);
                $insert_id=mysql_insert_id();
                $_SESSION['SESS_ID']=$insert_id;
                $_SESSION['sortitem']='id';
                $_SESSION['sortorder']='';
                $_SESSION['limit']='10';
                if ($remember == '1') {
                        setcookie("id", $result['id'], time()+(60*60*24*14));
                        setcookie("oid", sha1($oid), time()+(60*60*24*14));
                }
	}
	mysql_close($conn);
        echo '<meta http-equiv="refresh" content="0;url=index.php" />';
    	}
} catch(ErrorException $e) {
    echo $e->getMessage();
}

?>
